package middleware

import (
	"context"
	"fmt"
	"peilian-api/app/global/common"
	"peilian-api/app/global/log"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func SetLoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		uuidStr := strings.ReplaceAll(uuid.NewString(), "-", "")
		urlPath := c.Request.URL.Path
		ctx := context.WithValue(context.Background(), common.TraceKey, &log.Trace{TraceId: uuidStr, SpanId: uuidStr, Caller: urlPath})
		c.Set(common.TraceKey, ctx)

		c.Next()
		cost := time.Since(start).Milliseconds()
		u, exists := c.Get("uid")
		if !exists {
			u = 0
		}
		log.Logger.InfoF(c, fmt.Sprintf("user_id: %d, status: %d, Method: %s, IP:%s, Path:%s, Cost:%d ms", u, c.Writer.Status(), c.Request.Method, c.ClientIP(), urlPath, cost))
	}
}
